﻿using GDGeek;

using MrPP.SerriedCabinet;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;


namespace MrPP.SerriedCabinet
{

    
    public class AsyncTask:Task{


        System.Threading.Tasks.Task task_;
        public AsyncTask(Func<System.Threading.Tasks.Task> creater) {
           // task_ = task;
            this.init = delegate
            {
                task_ = creater();
            };
            this.isOver = delegate
            {
                return task_.IsCanceled || task_.IsCompleted;
            };
        }

    }

    public class SearchWindow : GDGeek.Singleton<SearchWindow>
    {
       // [SerializeField]
      //  private SearchModel _model;
        public Action<string> OnInput {
            get;
            set;
        }
        public void onInput() {
            string input = _input.text;
            string ot = "";
            for (int i = 0; i < input.Length; ++i)
            {
                char c = input[i];
                if ((c <= 'Z' && c >= 'A') || c <= 'z' && c >= 'a')
                {
                    ot += c;
                }
            }

            OnInput?.Invoke(ot.ToUpper());
            _input.text = ot.ToUpper();
        }
     /*   public struct Context {
            //public string abbr;
            public ArchivesData[] datas;
            public int selected;
            public ArchivesData data{
                get {
                    return datas[selected];
                }
            }
        }*/
       // private Context context_;

        [SerializeField]
        private Microsoft.MixedReality.Toolkit.UI.ProgressIndicatorOrbsRotator _progress;
        [SerializeField]
        private SearchMenu _menu;
        [SerializeField]
        private SearchControl _control;
        private FSM fsm_ = new FSM();
        public void doInput(string last, string next) {
            doInput(next);
        }
        public void refresh() {

            _menu.setup(Model.Instance.search.datas, this.doItemClicked);
        }
        void Start() {
            //fcontext_.selected = -1;
            /*fsm_.addState("input", input());
            fsm_.addState("normal", normal(), "input");
            fsm_.addState("selected", selected(), "input");
            fsm_.addState("open", open(), "input");
            fsm_.addState("loading", loading());
            fsm_.init("normal");*/
            Model.Instance.search.onInput += doInput;
            Model.Instance.search.onRefresh += refresh;
            Model.Instance.search.onSelected += doSelected;
        }

        private void doSelected(int last, int next)
        {
            if (next == -1)
            {
                _menu.release();

                _control.guide.SetActive(false);
            }
            else {
                  
                _menu.selected(next);
                _control.guide.SetActive(true);
            }
        }

        /*
private StateBase open()
{
   State state = TaskState.Create(delegate {
       return BoxRoot.Instance.open(context_.data);
   }, this.fsm_, "selected");

   return state;
}

private StateBase selected()
{
   State state = new State();
   state.onStart += delegate
   {
       _menu.selected(context_.selected);
       _control.guide.SetActive(true);
   };
   state.onOver += delegate
   {
       _menu.release();
       _control.guide.SetActive(false);
   };


   state.addAction("guide", "open");
   return state;
}

private StateBase normal()
{

   State state = new State();
   return state; 
}*/
        public Action<string> AddLetter {
            get;
            set;
        }
        public void doAddLetter(string letter)
        {
            _input.text += letter;
            //Debug.LogError(letter);
           // refresh();
            //fsm_.post("add_letter", letter);
            // AddLetter?.Invoke(letter);
        }
        public void doInput(string input) {
            if (input != _input.text) {
                _input.text = input;
            }
        }
        public void addLetter(string letter) {
           
        }
        /*
        public void doClear()
        {
            fsm_.post("clear");
         
        }*/
        /*
        private void clear() {
            _input.text = "";

        }
        public void doSearch()
        {
            fsm_.post("search");
        }
     
        public void doGuide()
        {
            fsm_.post("guide");
        }
        */
        public Action<int> onSelected {
            get;
            set;
        }
        private void doItemClicked(int id) {
            onSelected?.Invoke(id);
            /*
            if (context_.selected != id)
            {
                context_.selected = id;
                BoxRoot.Instance.highlight(context_.data);
            }
            else {
                context_.selected = -1;
                BoxRoot.Instance.lowlight();
            }
            Debug.LogWarning("selected!");
            this.fsm_.post("selected");*/
        }
        /*
        private StateBase loading()
        {

            State state =  TaskState.Create(delegate {
                Task task =  loadTask(search(this._input.text.ToLower()));
                TaskManager.PushBack(task, delegate
                {
                    _menu.setup(context_.datas, this.doItemClicked);
                });
                return task;
            }, this.fsm_, "input");

            return state;
        }*/
        /*
        private StateBase input()
        {
            State state = new State();
            state.addAction("add_letter", delegate(FSMEvent evt) {
                addLetter((string)evt.obj);
            });

            state.addAction("clear", delegate (FSMEvent evt) {
                clear();
            });
            state.addAction("selected", delegate
            {
                Debug.LogWarning("selected!" + context_.selected);
                if (context_.selected == -1)
                {
                       
                    return "normal";
                }
                else {
                    return "selected";
                }
            });
            state.addAction("search", delegate (FSMEvent evt) {
                Debug.LogWarning("search!");
                return "loading";
            });
            

            return state;
        }*/
        [SerializeField]
        private TMP_InputField _input;
      
        
        public Task loadTask(Task task) {
            TaskList tl = new TaskList();
            tl.push(new AsyncTask(delegate { return _progress.OpenAsync(); }));
            tl.push(task);
            tl.push(new AsyncTask(delegate { return _progress.CloseAsync(); }));

            TaskManager.PushFront(tl, delegate
            {
                _progress.gameObject.SetActive(true);
            });

            TaskManager.PushBack(tl, delegate
            {
                _progress.gameObject.SetActive(false);
            });
            return tl;
        }
       

       

        /*
       // private ArchivesData[] datas_ = null;
        public Task search(string word) {

            if (string.IsNullOrEmpty(word)) {
                return new Task();
            }
            string uri = Restful.RestfulManager.Uri("archives");
            var op = Restful.RestfulManager.Instance.options(uri, new System.Collections.Generic.Dictionary<string, string> { { "abbr", word }});
            var task = Restful.RestfulManager.Instance.getArrayTask<ArchivesData>(op, delegate (ArchivesData[] datas)
            {
                context_.datas = datas;

            });
            return task;
        }*/
    }
}